/*
 * @lc app=leetcode.cn id=8 lang=typescript
 *
 * [8] 字符串转换整数 (atoi)
 */

// @lc code=start
function myAtoi(s: string): number {
    let toggle = false;
    let way = "+";
    let result: string[] = [];
    const tag = [...Array(10).keys()].map((i) => i.toString());
    for (let i of s.split("")) {
        if (i === " ") {
            if (toggle) {
                break;
            } else {
                continue;
            }
        } else if (!toggle && ["+", "-"].includes(i)) {
            toggle = true;
            way = i;
            continue;
        } else if (tag.includes(i)) {
            toggle = true;
            if (result.length == 0 && i === "0") {
                continue;
            }
            result.push(i);
            continue;
        }
        break;
    }
    if (result.length === 0) return 0;
    const final = parseInt(way + result.join(""), 10);
    if (final <= -(2 ** 31)) {
        return -(2 ** 31);
    } else if (final >= 2 ** 31 - 1) {
        return 2 ** 31 - 1;
    } else {
        return final;
    }
}
// @lc code=end
